package com.jie.commonlib.support.permission;

import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import com.tbruyelle.rxpermissions3.RxPermissions;
import java.util.ArrayList;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.content.PermissionChecker;
import androidx.fragment.app.Fragment;
import io.reactivex.rxjava3.functions.Consumer;


/**
 * 权限检查工具类
 * 当Build.VERSION.SDK_INT(系统实际ROM)小于23的时候,无法判断权限.只能通过异常.参看微信.
 * 当Build.VERSION.SDK_INT>23 && targetSdkVersion<23 使用PermissionChecker.checkSelfPermission方法判断
 * 当Build.VERSION.SDK_INT>23 && targetSdkVersion>23 使用ContextCompat.checkSelfPermission方法判断
 * @author jie
 */
public class PermissionHelper {

    /**
     * 校验权限是否给予
     *
     * @param permissions 申请的权限集合
     * @return true: 申请的权限已经全部都给了，false：有部分权限没有给
     */
    public static boolean check(Context context, String... permissions) {
        String[] needRequestList = getNeedRequestList(context, permissions);
        return needRequestList == null || needRequestList.length == 0;
    }

    /**
     * 获取需要申请的权限集合
     */
    public static String[] getNeedRequestList(Context context, String... permissions) {
        ArrayList<String> needRequestList = new ArrayList<>();
        for (String permission : permissions) {
            // targetSdkVersion < 23 和 > 23 使用不同的判断
            if (context.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.M) {
                if (PermissionChecker.checkSelfPermission(context, permission) != PermissionChecker.PERMISSION_GRANTED) {
                    needRequestList.add(permission);
                }
            } else {
                if (ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED){
                    needRequestList.add(permission);
                }
            }
        }
        return needRequestList.toArray(new String[needRequestList.size()]);
    }

    /**
     * 先判断是否有权限未获取，然后发起请求权限
     * @param callBack 回调
     * @param activity 当前活动
     * @param permissions 权限申请集合
     */
    public static void request(final CallBack callBack, AppCompatActivity activity, final String... permissions){
        // 从需要申请的权限中 获取没有授予过得权限
        final String[] deniedPermissions = getNeedRequestList(activity, permissions);
        if (deniedPermissions != null && deniedPermissions.length > 0){
            RxPermissions rxPermissions = new RxPermissions(activity);
            request(callBack, rxPermissions, activity, permissions);
        } else{// 所有权限都有，直接返回true
            callBack.success();
        }
    }

    /**
     * 先判断是否有权限未获取，然后发起请求权限
     * @param callBack 活动
     * @param fragment 当前碎片
     * @param permissions 权限申请集合
     */
    public static void request(final CallBack callBack, Fragment fragment, final String... permissions){
        // 从需要申请的权限中 获取没有授予过得权限
        Context context = fragment.getContext();
        final String[] deniedPermissions = getNeedRequestList(context, permissions);
        if (deniedPermissions != null && deniedPermissions.length > 0){
            RxPermissions rxPermissions = new RxPermissions(fragment);
            request(callBack, rxPermissions, context, permissions);
        } else{// 所有权限都有，直接返回true
            callBack.success();
        }
    }

    /**
     * 发起请求权限
     * @param rxPermissions 权限申请对象
     * @param context 上下文
     * @param permissions 权限申请集合
     */
    private static void request(final CallBack callBack, RxPermissions rxPermissions,
                                final Context context,  final String... permissions) {
        rxPermissions.request(permissions)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean success) throws Exception {
                        if (success){ // 权限申请成功
                            if (check(context, permissions)) { // 再检查一遍权限
                                callBack.success();
                            }else{ // 检查后发现有权限没有授予，失败
                                callBack.fail(permissions);
                            }
                        }else{ // 权限申请失败
                            callBack.fail(permissions);
                        }
                    }
                });
    }

    public interface CallBack{
        /**
         * 权限申请成功
         */
        void success();

        /**
         * 权限申请失败
         * @param permissions 失败权限集合
         */
        void fail(String... permissions);
    }
}
